﻿fs.insert = function (insert) {

    /*
    submit upgrade
    1 添加一个新的handler 用于区分每一个不同的insert表单
    */
    insert.handler = {
        functions: [{ type: "AIA", list: "SUBARAPINTERCOAGING" },
        { type: "PID", list: "SubPurchaseIntercoDeclaration" },
        { type: "SID", list: "SubSalesIntercoDeclaration" },
        { type: "TSBR", list: "SubTradeSalesByRGC" },
        { type: "PSBR", list: "SubProductSalesByRGC" }
        ],
        set: function (args) {
            this.functions.push(args);
        },
        get: function (t) {
            for (var i = 0; i < this.functions.length; i++) {
                if (this.functions[i].type == t)
                    return this.functions[i];
            }
        }
    };
    insert.submit = function (t) {

        fs.ui.mask("#s4-workspace", "processing...");
        var handler = insert.handler.get(t);
        var round = 0, allRound = 0, mit = 0, allSaved = false;

        //delete items
        var url = fs.sys.siteUrl + "/_vti_bin/ListData.svc/" + handler.list;
        insert.deleteItem(url, fs.receiver.toBeDelete);

        var allSubRow = $("tr[subrow]");
        allRound = allSubRow.length;

        $(allSubRow).each(function () {
            var item = {}, beforeSendFunction;
            url = fs.sys.siteUrl + "/_vti_bin/ListData.svc/" + handler.list;
            var self = $(this);

            item.AccountCode = self.attr("subrow");
            var selector = self.find(".fs-picker");
            $(selector).each(function () {
                var sect = $(this);
                item[sect.attr('type')] = sect.find("option:selected").text();
            })

            item.CompanyCode = fs.form.companycode; //use parent form value
            item.Year = fs.form.year;
            item.Month = fs.form.month;
            //check if update
            var locationId = self.attr("sourceId");
            var etag = self.attr("etag");
            if (locationId) {
                // Update the existing Part location.
                url = url + "(" + locationId + ")";
                beforeSendFunction = function (xhr) {
                    xhr.setRequestHeader("If-Match", etag);
                    // Using MERGE so that the entire entity doesn't need to be sent over the wire. 
                    xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
                }
            } else {
                item["Title"] = fs.form.companycode + "_" + fs.form.year + fs.form.month;
            }
            //process all field
            self.find("td[refrence]").each(function () {
                var self = $(this);
                var refrenceFieldName = self.attr("refrence");
                var value = fs.util.getValue(self);
                // value = typeof value == "string" ? String.format("'{0}'", value) : value;

                item[refrenceFieldName] = value;
            });

            var body = Sys.Serialization.JavaScriptSerializer.serialize(item);

            $.ajax({
                type: 'POST',
                url: url,
                contentType: 'application/json',
                processData: false,
                cache: false,
                async: false,
                beforeSend: beforeSendFunction,
                data: body,
                success: function () {
                    round++;
                    allSaved = round == allRound;
                    fs.util.log('Saved.all Saved ? ' + allSaved);
                },
                error: function (e) {
                    fs.util.log(e.responseText);
                }
            });
        });

        var savingID = setInterval(function () {
            if (allSaved) {
                clearInterval(savingID);
            }

            mit++;
            fs.util.log("Saveing..." + mit * 500);
        }, 500);

        fs.ui.clear("#s4-workspace");
    }
    insert.monthReceiver = function (t) {

        var handler = insert.handler.get(t);

        //remove all subrow
        $("tr[subrow]").remove();
        //reset lastMonth 
        fs.receiver.lastMonth = [];

        //get current page sub entity data from selected month , i.e:lm ytdm1 ...
        var allTRWithSubEntity = $("tr[subentity=true]");
        $(allTRWithSubEntity).each(function () {
            var self = $(this);
            var accountCode = self.attr("accountcode");
            var identity = self.attr("identity");
            var insertType = self.attr("insertType");
            fs.receiver.getSubEntityByAccountCode(
                {
                    accountcode: accountCode,
                    year: fs.form.year,
                    list: handler.list,
                    month: fs.form.month,
                    companycode: fs.form.companycode
                }
                , function (receiveSubEntitys) {
                    receiveSubEntitys = receiveSubEntitys.d.results;
                    if (receiveSubEntitys.length == 0) return;
                    fs.receiver.lastMonth = fs.receiver.lastMonth || [];
                    var lastMonth = fs.util.search(receiveSubEntitys, "Month", fs.form.month - 1);
                    $(lastMonth).each(function () {
                        fs.receiver.lastMonth.push(this);
                    });
                    var thisMonth = fs.util.search(receiveSubEntitys, "Month", fs.form.month);
                    var fs_insert_template = "";
                    if (fs.form.mode == "DISPLAY") {
                        fs_insert_template = "#insert-display-row";
                    } else {
                        fs_insert_template = "#insert-edit-row"; 
                    }

                    $(thisMonth).each(function () {
                        this.identity = identity;
                        this.insertType = insertType;
                        this.fs_insert_template = fs_insert_template;
                        this.fs_insert_template_type = self.attr("template");
                        this.Scope = "scope=" + self.attr("scope");

                        self.before(fs_MakeEditRowTemplate(this));

                    });
                    $(".fs-picker").change();
                }); //return SUBAIA entity list

        });
        if (fs.form.mode == "DISPLAY")
            $("input,select").attr("disabled", "");
    }
    window.fs_insert_pickerValueChange = function (obj) {
        var self = $(obj);
        var value = self.find("option:selected").text();
        self.next().text(value);
    }
    window.fs_insert_picker = insert.picker = function (v, c) {
        if (!v) return "";
        return v.toUpperCase() == c.toUpperCase() ? "selected" : "";
    }
    window.fs_description_by_rgc = function (rgc) {
        var rgcs = fs.util.search(fs.form.allRGC, "RGC", rgc);
        if (rgcs.length > 0)
            return rgcs[0].Description;
        else
            return "";
    }
    window.fs_insert_deleteItem = insert.deleteItem = function (url, ids) {
        if (!ids) return;
        var round = 0, allRound = ids.length, mit = 0, allSaved = false;

        $(ids).each(function (i, id) {
            $.ajax({
                type: "DELETE",
                url: url + "(" + id + ")",
                async: false,
                contentType: "application/json",
                success: function () {
                    round++;
                    allSaved = round == allRound;

                    // fs.util.log(id + "-Deleted all Saved ? " + allSaved);
                },
                error: function (xhr) {
                    // fs.util.log(xhr.status + ': ' + xhr.statusText);
                }
            });
        });

        //        var savingID = setInterval(function () {
        //            if (allSaved) {
        //                clearInterval(savingID);
        //            }

        //            mit++;
        //            // fs.util.log("Saveing..." + mit * 500);
        //        }, 500);

        //        while (!allSaved) {

        //        }
    }

    window.fs_insert_receiveValue = insert.receiveValue = function (args) {
        if (!args.datasource) return;

        for (var i = 0; i < args.datasource.length; i++) {
            var entity = args.datasource[i];
            args.entity.set(0.00);

            var pass = fs.util.ref(entity, "accountcode") == args.entity.accountcode;
            if (!pass) continue;

            for (f in args.entity.allCompareField) {
                var entityFieldValue = fs.util.ref(entity, f);
                var compreFieldValue = args.entity.allCompareField[f];

                pass = entityFieldValue == compreFieldValue;
                if (!pass)
                    break;
            }

            if (!pass) continue;
            var CM_Value = "CM_" + args.entity.identity;
            var YTDM1_Value = "YTDM1_" + args.entity.identity;

            //设置字符串类型
            if (args.entity.type == "YTDM1_IC") {
                var value = fs.util.ref(entity, CM_Value)
                args.entity.set(value);
                return;
            }

            CM_Value = parseFloat(fs.util.ref(entity, CM_Value));
            YTDM1_Value = parseFloat(fs.util.ref(entity, YTDM1_Value));

            CM_Value = (!CM_Value && CM_Value.toString().trim() == "") ? 0 : CM_Value;
            YTDM1_Value = (!YTDM1_Value && YTDM1_Value.toString().trim() == "") ? 0 : YTDM1_Value;

            var controlValue = CM_Value;
            if (args.entity.receivetype == "YTDM1") {
                if (args.entity.type == "YTDM1_IC")
                    controlValue = CM_Value;
                else
                    controlValue += YTDM1_Value;
            }
            args.entity.set(controlValue);
            return;

        }
    }

    window.fs_insert_getCurrentMonthValue = insert.getCurrentMonthValue = function (field, companyname, accountcode, entity) {
        var value = 0.00;

        var cac = fs.util.ref(entity, "accountcode");
        var cname = fs.util.ref(entity, "CompanyName");
        if (cname == companyname && cac == accountcode) {
            value = fs.util.ref(entity, field);
            return value;
        }

        return value;
    }

    window.fs_insert_getLastMonthValue = insert.getLastMonthValue = function (field, companyname, accountcode) {
        var value = 0.00;
        for (var i = 0; i < fs.receiver.lastMonth.length; i++) {
            var entity = fs.receiver.lastMonth[i];

            var cac = fs.util.ref(entity, "accountcode");
            var cname = fs.util.ref(entity, "CompanyName");
            if (cname == companyname && cac == accountcode) {
                value = fs.util.ref(entity, field);
                return value;
            }
        }
        return value;
    }
    window.fs_insert_tobeRemoveRow = insert.tobeRemoveRow = function (obj) {
        if (confirm("are you sure delete this item ?")) {
            var sourceId = $(obj).parents("tr[sourceId]").attr("sourceId");

            fs.receiver.toBeDelete = fs.receiver.toBeDelete || [];
            fs.receiver.toBeDelete.push(sourceId);
            fs_insert_removeRow(obj);
        }
    }
    window.fs_insert_removeRow = insert.removeRow = function (row) {

        $(row).parents("tr[subrow]").remove();
        fs.calc.equs.refresh("NEXT");
        fs.calc.equs.refresh("PREV");
        fs.calc.equs.refresh("UNTIL");
    }
    window.fs_insert_getValue = insert.getValue = function (item, field) {
        var value = fs.util.ref(item.data, field);
        return value.toString().commafy();
    }
    return insert;
} (fs.insert || {});